package com.imooc.springcloud;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import sun.dc.pr.PRError;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author L
 */
@RestController
@Slf4j
@RequestMapping("gateway/")
public class GateWayController {

    public static final Map<Long, Product> items = new ConcurrentHashMap<>();

    @GetMapping("details")
    public Product get(@RequestParam("pid") Long pid) {
        if (!items.containsKey(pid)) {
            Product product = Product.builder()
                    .productId(pid)
                    .description("好吃不贵")
                    .stock(100L)
                    .build();
            items.putIfAbsent(pid, product);
        }
        return items.get(pid);
    }

    @PostMapping("placeOrder")
    public String buy(@RequestParam("pid") Long pid) {
        Product product = items.get(pid);
        if (product == null) {
            return "not found";
        } else if (product.getStock() <= 0) {
            return "sold out";
        }
        synchronized (product) {
            if (product.getStock() <= 0) {
                return "sold out";
            }
            product.setStock(product.getStock() - 1);
        }
        return "order placed";
    }
}
